<?php
namespace BaseBundle\Model;

use RedUnicorn\SymfonyKernel\Model\Model;
use Symfony\Component\DependencyInjection\ContainerInterface;
use RedUnicorn\Validate\Validate;
use BaseBundle\Entity\Store;

class m_store extends Model 
{

    /**
     * @var Store
     */
    private $store_class = null;

    function __construct(ContainerInterface $container)
    {   

        parent::__construct($container, 'store');
    }
 
    public function validate($data, $id = false)
    {
        $this->entityManager = $this->getDoctrine()->getManager();
        
        if(empty($id)){
            $this->store_class = new Store();
        }else{
            if(!$this->is_exist($id)){
                self::$error->setError($this->get('translator')->trans('未找到对应信息'));
                return false;
            }

            $this->store_class = $this->entityManager->getRepository(Store::class)->find($id);
        }
                
        if(array_key_exists('store_name', $data)){
            $this->store_class->setStoreName($data['store_name']);
        }
        
        if(self::$error->validate($this->store_class)){
            return false;
        }
        
        return true;
    }
    
    public function insert($data)
    {
        if(!$this->validate($data)){
            return false;
        }
        
        
        $this->entityManager->persist($this->store_class);
        $this->entityManager->flush();
    
        $this->lastInsertId = $this->store_class->getId();

        return true;
    }
    
    public function update($id ,$data)
    {
        if(empty($id)){
            self::$error->setError('param id is not null');
            return false;
        }
        
        if(!$this->validate($data, $id)){
            return false;
        }
        
        $this->entityManager->flush();

        return true;
    }
    
    public function rewritesRule(&$rule)
    {   
                    
        //TODO where   
        if(array_key_exists('id', $rule) && !empty($rule['id'])){
           $this->sql_array['where'] .= " AND sql_pre.id = '{$rule['id']}' ";
        }
                    
        //TODO where   
        if(array_key_exists('store_name', $rule) && !Validate::isRealEmpty($rule['store_name'])){
            $this->sql_array['where'] .= " AND sql_pre.store_name LIKE '{$rule['store_name']}' ";
        }
            
    }
       

    
}